import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式
import {
  Message
} from 'element-ui'
import {
  getToken
} from '@/utils/auth' // 验权
import adminApi from '@/api/admin/adminUser'

const whiteList = ['/login', '/o', '/info']
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    if (to.path === '/login') {
      next({
        path: '/'
      })
    } else if (from.path !== '/' && to.matched.length === 0) {
      NProgress.done()
      next(new Error('你没有权限访问'))
    } else {
      if (store.getters.roles.length === 0) {
        adminApi.getInfo().then(resp => {
          const data = resp.data
          if (!data.roles || data.roles.length <= 0) {
            data.roles = [{
              name: '无角色'
            }]
          }
          store.dispatch('GetInfo', data)
          var {
            roles,
            menus
          } = data
          store.dispatch('GenerateRoutes', {
            roles,
            menus
          }).then(() => {
            router.addRoutes(store.getters.addRouters)
            next({
              ...to
            })
          })
        }).catch(error => {
          NProgress.done()
          store.dispatch('FedLogOut')
          const message = (error && error.message) ? error.message : '登录已超时，请重新登录'
          Message({
            message,
            type: 'warning'
          })
          next({
            name: 'login',
            params: {
              lastPath: to.fullPath
            }
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.findIndex(i => to.path.startsWith(i)) >= 0) {
      next()
    } else {
      NProgress.done()
      next({
        name: 'login',
        params: {
          lastPath: to.fullPath
        }
      })
    }
  }
})

router.afterEach((to, from) => {
  store.dispatch('updateCurrentMenu', to.meta)
  NProgress.done() // 结束Progress
})

router.onError(err => {
  console.error(err)
  NProgress.done()
  Message({
    message: '页面加载失败或你当前页面没有权限，请稍后重试',
    type: 'warning'
  })
})
